package info.hexin.jdk.scheduledexecutorservice;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by infi.he on 2015/4/15.
 */
public class ScheduledExecutorServiceTest {
    private final static String threadNamePrefix = "test_";

    static ScheduledExecutorService scheduledExecutorService = Executors
            .newScheduledThreadPool(3, new ThreadFactory() {
                private final AtomicLong threadIndex = new AtomicLong(0);

                public Thread newThread(Runnable r) {
                    return new Thread(r, threadNamePrefix + this.threadIndex.incrementAndGet());
                }
            });

    public static void main(String[] args) {
        final AtomicLong index = new AtomicLong(0);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                //每次调用都是同一个对象
                System.out.println("11111" + (new Date().toString()) + "--" + index.getAndIncrement());
                try {
                    //如果一个任务时间太长，那么会导致
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 1, 2, TimeUnit.SECONDS);

        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("22222" + (new Date().toString()) + "--" + index.getAndIncrement());
                try {
                    //如果一个任务时间太长，那么会导致
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 1, 1, TimeUnit.SECONDS);
    }
}
